#include <boost/lexical_cast.hpp>

#include "Connection.h"
#include "Header.h"

namespace HTTP_SERVER {
    
    Connection::Connection(boost::asio::ip::tcp::socket socket) : clientSocket_(std::move(socket)) {

    }

    void Connection::start(){
        const char name_value_separator[] = { ':', ' ' };
        const char crlf[] = { '\r', '\n' };
        std::vector<boost::asio::const_buffer> buffers;
        buffers.push_back(boost::asio::buffer("HTTP/1.0 200 OK\r\n"));
        std::vector<Header> headers;
        std::string content("<html><head><title>Created</title></head><body><h1>hello, Welcome to your first C++ HTTP Server</h1></body></html>");
        Header h1;
        h1.name = "Content-Length" ;
        h1.value = boost::lexical_cast<std::string>(content.size());
        Header h2;
        h2.name = "Content-Type";
        h2.value = "text/html";
        headers.push_back(h1);
        headers.push_back(h2);
        
        for (std::size_t i = 0; i < headers.size(); ++i)
        {
          Header& h = headers[i];
          buffers.push_back(boost::asio::buffer(h.name));
          buffers.push_back(boost::asio::buffer(name_value_separator));
          buffers.push_back(boost::asio::buffer(h.value));
          buffers.push_back(boost::asio::buffer(crlf));
        }
        buffers.push_back(boost::asio::buffer(crlf));
        buffers.push_back(boost::asio::buffer(content));
        
        boost::asio::async_write(clientSocket_, buffers, 
                [this](boost::system::error_code ec, std::size_t)
                {
                  if (!ec)
                  {
                    // Initiate graceful connection closure.
                    boost::system::error_code ignored_ec;
                    clientSocket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both,
                      ignored_ec);
                  }

                });
    }
    
};
